package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.feign.ApAuthorFeign;
import com.heima.user.feign.WmUserFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.common.constants.user.UserConstants.AdminConstans;
import com.heima.common.exception.CustomException;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.service.ApUserRealnameService;
import com.heima.model.wemedia.pojos.WmUser;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 王可
 * @Date: 2021/01/25/20:37
 * @Description:
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Resource
    private ApUserMapper apUserMapper;

    @Resource
    WmUserFeign wemediaFeign;

    @Resource
    ApAuthorFeign articleFeign;

    /**
     * 根据状态分页查询用户审核
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //判断参数是否正确
        if (dto == null) {
            //不正确返回对应的错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //封装查询条件
        //封装分页条件
        Page<ApUserRealname> pageResult = new Page<>(dto.getPage(), dto.getSize());
        //封装查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }

        IPage<ApUserRealname> pageResponse = page(pageResult, queryWrapper);

        //封装查询结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResponse.getTotal());
        pageResponseResult.setData(pageResponse.getRecords());

        //返回查询结果
        return pageResponseResult;
    }

    @Override
    @GlobalTransactional //seata分布式事务注解
    public ResponseResult updateByStatus(AuthDto dto) {
        //检查参数
        if (dto == null) {

            //参数为空，返回对应的错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //检查审核用户的状态码
        boolean flag = checkStatus(dto.getStatus());

        if (!flag) {

            //如果返回的是false，说明状态码不对，返回对应的错误数据给前端
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据id修改ap_user-realName
        ApUserRealname apUserRealname = new ApUserRealname();

        apUserRealname.setId(dto.getId());

        apUserRealname.setStatus(dto.getStatus());

        if (StringUtils.isNotBlank(dto.getMsg())) {
            //审核失败的原因，只有审核失败才会有msg
            apUserRealname.setReason(dto.getMsg());
        }

        updateById(apUserRealname);

        //审核通过的话，需要同步到wemedia和article中
        if ((AdminConstans.PASS_AUTH).equals(dto.getStatus())) {

            createWemediaAndArticle(dto.getId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 参数不能为空，必须是2或者9
     *
     * @param status
     * @return
     */
    public boolean checkStatus(Short status) {

        if (status == null || (!(AdminConstans.FAIL_AUTH).equals(status) && !status.equals(AdminConstans.PASS_AUTH))) {

            return false;
        }
        return true;
    }

    public void createWemediaAndArticle(Integer id) {

        //根据id获取realName表中的user_id，在关联查到ap_user中的数据
        ApUserRealname realname = getById(id);

        Integer userId = realname.getUserId();

        // 调用公安部实名认证接口，识别该用户身份信息是否正确
//        boolean checkIdcard = IdCardUtils.checkIdCardInfo(realname.getName(), realname.getIdno());
//        if (!checkIdcard){
//            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户身份证信息错误"));
//        }

            //根据userId去ap_user中查用户
            ApUser apUser = apUserMapper.selectById(id);

            if (apUser == null) {

                //抛异常，不然事务不会成功回滚
                throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证用户相关信息不存在"));
            }

            //查自媒体用户是否存在，如果不存在，创建自媒体用户并保存
            WmUser wmUser = wemediaFeign.findByName(apUser.getName());
            if (wmUser == null) {
                wmUser = new WmUser();
                BeanUtils.copyProperties(apUser, wmUser);
                wmUser.setApUserId(userId);
                wmUser.setName(apUser.getName());
                wmUser.setPassword(apUser.getPassword());
                wmUser.setSalt(apUser.getSalt());
                wmUser.setImage(apUser.getImage());
                wmUser.setPhone(apUser.getPhone());
                wmUser.setStatus(9);// 正常可用
                wmUser.setType(0);
                wmUser.setCreatedTime(new Date());
                wemediaFeign.save(wmUser); // 创建自媒体用户
                createAuthor(wmUser);
            }
        }

        public void createAuthor (WmUser wmUser){

            // 1. 查询作者信息是否存在
            ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());

            //2. 为null代表作者不存在，创建一个作者
            if (apAuthor == null) {
                apAuthor = new ApAuthor();
                apAuthor.setName(wmUser.getName());
                apAuthor.setType(2);
                apAuthor.setUserId(wmUser.getApUserId());
                apAuthor.setCreatedTime(new Date());
                apAuthor.setWmUserId(wmUser.getId());
                articleFeign.save(apAuthor);
            }
        }
    }

